package botcraft.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConsoleClient extends Client {
	private static final Logger logger = Logger.getLogger(ConsoleClient.class.getName());
	private static final Pattern pattern = Pattern.compile("^(.+):(\\d+)$");
	
	private final BufferedReader input;
	
	public static void main(final String[] arguments) {
		Matcher matcher;
		if ((arguments.length < 1) || (!(matcher = pattern.matcher(arguments[0])).matches())) {
			System.err.println("Usage: java " + ConsoleClient.class.getName() + " <host>:<port>");
			return;
		}
		try {
			new ConsoleClient(matcher.group(1), Integer.parseInt(matcher.group(2))).run();
		} catch (ClassNotFoundException e) {
			logger.log(Level.SEVERE, "Error loading game", e);
		} catch (NumberFormatException e) {
			logger.log(Level.SEVERE, "Invalid port: " + matcher.group(2), e);
		} catch (IOException e) {
			logger.log(Level.SEVERE, "Error connecting to " + matcher.group(1) + ":" + matcher.group(2), e);
		}
	}
	
	public ConsoleClient(final String host, final int port) throws ClassNotFoundException, IOException {
		super(host, port);
		input = new BufferedReader(new InputStreamReader(System.in));
	}

	@Override
	protected String issueCommand() {
		try {
			return input.readLine();
		} catch (IOException e) {
			logger.log(Level.WARNING, "Error reading command from console", e);
			return null;
		}
	}
	
	@Override
	protected void executeCommand(final String command) {
		System.out.println("> " + command);
	}
}
